package cn.lpq.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.json.JSONUtil;

public class OcrCaptchaUtil {

	private static Logger logger = LoggerFactory.getLogger(OcrCaptchaUtil.class);

	public static String getYzm(String cookie) {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			logger.debug("正在识别验证码。。。");
			httpClient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet("http://lx.heikeyun.net/LgValidateCode.ashx");
			httpGet.setHeader("Cookie", cookie);
			response = httpClient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			// 原图
			// File verificationCodeTmpFile =
			// File.createTempFile(System.getProperty("java.io.tmpdir"), ".jpg");
			File verificationCodeTmpFile = new File(
					"D:\\tmp\\" + DateUtil.thisMinute() + DateUtil.thisSecond() + ".gif");
			verificationCodeTmpFile.deleteOnExit();
			FileOutputStream fileout = new FileOutputStream(verificationCodeTmpFile);
			byte[] buffer = new byte[2048];
			int ch = 0;
			while ((ch = is.read(buffer)) != -1) {
				fileout.write(buffer, 0, ch);
			}
			is.close();
			fileout.flush();
			fileout.close();
			// 处理过的
			//File verificationCodeTmpFileCL = File.createTempFile(System.getProperty("java.io.tmpdir"), ".jpg");
			File verificationCodeTmpFileCL =new File(
					"D:\\tmp\\" + DateUtil.thisMinute() + DateUtil.thisSecond() + ".jpg");
			verificationCodeTmpFileCL.deleteOnExit();
			BufferedImage img = ImgUtil.read(verificationCodeTmpFile);
			ImgUtil.write(img, verificationCodeTmpFileCL);
			// 去噪点
//			CaptchaUtil.removeBackground(verificationCodeTmpFile.getAbsolutePath(),
//					verificationCodeTmpFileCL.getAbsolutePath());
			// 裁剪边角
			// CaptchaUtil.cuttingImg(verificationCodeTmpFileCL.getAbsolutePath());
			String verificationCodeBase64 = Base64.encode(verificationCodeTmpFileCL);
			HttpPost httpPost = new HttpPost("https://nmd-ai.juxinli.com/ocr_captcha");
			httpPost.setHeader("Content-Type", "application/json");
			Map<String, String> param = new HashMap<String, String>();
			param.put("image_base64", verificationCodeBase64);
			param.put("app_id", "123456");
			param.put("ocr_code", "0000");
			String jsonstr = JSONUtil.toJsonStr(param);
			StringEntity se = new StringEntity(jsonstr);
			httpPost.setEntity(se);
			response = httpClient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() != 200) {
				logger.debug("识别验证码失败，正在重新识别");
				return getYzm(cookie);
			}
			entity = response.getEntity(); // 获取网页内容
			Map result = JSONUtil.toBean(EntityUtils.toString(entity, "UTF-8"), Map.class);
			String yzm = result.get("string").toString();
			EntityUtils.consume(entity);
			if (yzm.length() != 4) {
				logger.debug("识别验证码错误，正在重新识别");
				return getYzm(cookie);
			}
			response.close();
			httpClient.close();
			logger.debug("识别出的验证码为：" + yzm);
			return yzm;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("识别验证码发生异常，正在重新识别");
			return getYzm(cookie);
		} finally {
			try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
